@on_task Decorator
The @on_task decorator provides a simple way to register functions as event-driven task handlers for agent deployment and background task processing.Overview
The@on_task
decorator automatically:
- Registers your function as a task handler
- Sets up event listening for incoming task execution requests
- Handles both synchronous and asynchronous functions
- Validates that the decorated function has a
task
parameter - Works with default configuration from environment variables
Syntax
Parameters
The decorator itself takes no parameters, but the decorated function must:- Accept a
task
parameter as its first argument - Return the modified task object
Usage Examples
Basic Synchronous Handler
Asynchronous Handler
Task Processing with Error Handling
Processing Different Input Types
Using Optional Internal Status for Context Information
Using Internal Status with Explicit Saving
Behavior
Automatic Event Listening
When you use the@on_task
decorator, it automatically:
- Sets up event listening for your agent
- Waits for incoming task execution requests
- Calls your decorated function when tasks arrive
- Handles the task lifecycle (status updates, result saving)
Function Requirements
Your decorated function must:- Accept a
task
parameter - Return the modified task object
- Handle any exceptions internally (recommended)
Configuration
The decorator uses:- Environment variables for SDK configuration (
XPANDER_API_KEY
,XPANDER_ORGANIZATION_ID
, etc.) - Default agent ID from
XPANDER_AGENT_ID
environment variable
Task Object Properties
Thetask
parameter passed to your function contains:
Best Practices
1. Always Return the Task
2. Handle Errors Gracefully
3. Set Appropriate Status
4. Validate Input
5. Use Internal Status Optionally for Context Information
Related Types
- [
AgentExecutionStatus
](/API reference/types#agentexecutionstatus): Task execution statuses - [
AgentExecutionInput
](/API reference/types#agentexecutioninput): Task input structure - [
OutputFormat
](/API reference/types#outputformat): Output format options
Related Documentation
- [Events Module](/API reference/events): Full events module documentation
- [Tasks Module](/API reference/tasks): Task management and execution
- [Agents Module](/API reference/agents): Agent creation and management